#include <stdio.h>
#include "http.h"

//发送GET请求
//url: 请求地址
//headers: 增加的请求头部字段
//psize: 响应正文大小，输出参数
//返回值: 响应正文，需要调用者释放内存
char* get(char* url, struct curl_slist* headers, size_t* psize)
{
    char *respdata;
    size_t respsize;
    FILE *fp = open_memstream(&respdata, &respsize);
    if (!fp)
    {
        perror("open_memstream");
        return NULL;
    }

    CURL *client = curl_easy_init();
    if (!client)
    {
        perror("curl_easy_init");
        fclose(fp);
        return NULL;
    }

    curl_easy_setopt(client, CURLOPT_URL, url);

    if (headers)
    {
        curl_easy_setopt(client, CURLOPT_HTTPHEADER, headers);
    }

    // 将服务器返回的响应报文保存到文件流中
    curl_easy_setopt(client, CURLOPT_WRITEDATA, fp);

    CURLcode error = curl_easy_perform(client);
    if (error != CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform: %s\n", curl_easy_strerror(error));
        curl_easy_cleanup(client);
        fclose(fp);
        return NULL;
    }

    curl_easy_cleanup(client);
    fclose(fp);

    //更新响应正文大小
    *psize = respsize;

    return respdata;
}

//发送POST请求
//url: 请求地址
//headers: 增加的请求头部字段
//data: 请求正文
//psize: 请求和响应正文大小，输入和输出参数
//返回值: 响应正文，需要调用者释放内存
char* post(char* url, struct curl_slist* headers, char* data, size_t* psize)
{
    char *respdata;
    size_t respsize;
    FILE *fp = open_memstream(&respdata, &respsize);
    if (!fp)
    {
        perror("open_memstream");
        return NULL;
    }

    CURL *client = curl_easy_init();
    if (!client)
    {
        perror("curl_easy_init");
        fclose(fp);
        return NULL;
    }

    curl_easy_setopt(client, CURLOPT_URL, url);
    curl_easy_setopt(client, CURLOPT_POST, 1);
    curl_easy_setopt(client, CURLOPT_POSTFIELDS, data);
    curl_easy_setopt(client, CURLOPT_POSTFIELDSIZE, *psize);

    if (headers)
    {
        curl_easy_setopt(client, CURLOPT_HTTPHEADER, headers);
    }

    // 将服务器返回的响应报文保存到文件流中
    curl_easy_setopt(client, CURLOPT_WRITEDATA, fp);

    CURLcode error = curl_easy_perform(client);
    if (error != CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform: %s\n", curl_easy_strerror(error));
        curl_easy_cleanup(client);
        fclose(fp);
        return NULL;
    }

    curl_easy_cleanup(client);
    fclose(fp);

    //更新响应正文大小
    *psize = respsize;

    return respdata;
}